package com.leetcode.algorithm.y22.m08.w3;

import com.leetcode.algorithm.common.TreeNode;

/**
 * 236. 二叉树的最近公共祖先
 * 
 * https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/
 * 
 * @author jie.deng
 *
 */
class Question0236Solution02 {

	public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
		if (root == null || p == root || q == root) {
			return root;
		}
		// 后序遍历
		TreeNode left = lowestCommonAncestor(root.left, p, q);
		TreeNode right = lowestCommonAncestor(root.right, p, q);
		if (left == null && right == null) {
			return null;
		} else if (left == null) {
			return right;
		} else if (right == null) {
			return left;
		}
		return root;
	}

}